package pub.cleangao.common.util;

import com.alibaba.fastjson2.JSONObject;
import com.google.gson.*;
import lombok.SneakyThrows;

import java.lang.reflect.Type;

public class JsonUtil {

    static GsonBuilder gb = new GsonBuilder();

    static {
        gb.registerTypeAdapter(Class.class, new ClassCodec());
        gb.disableHtmlEscaping();
    }

    public static String pojoToJson(Object obj) {
        return gb.create().toJson(obj);
    }

    public static <T> T jsonToPojo(String json, Class<T> clazz) {
        return JSONObject.parseObject(json, clazz);
    }


    /**
     * 需要实现 JsonSerializer，JsonDeserializer 序列化和反序列化接口
     * 泛型 Class<?> 是说要把 java 那个类型序列化反序列化
     */
    private static class ClassCodec implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {

        // 反序列化
        @SneakyThrows
        @Override
        public Class<?> deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            String clazz = jsonElement.getAsString();
            return Class.forName(clazz);
        }

        // 序列化
        @Override
        public JsonElement serialize(Class<?> aClass, Type type, JsonSerializationContext jsonSerializationContext) {
            // 将 Class 变为 json
            return new JsonPrimitive(aClass.getName());
        }
    }
}
